package com.hk.Mgr.web.controller.app;

import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ResultCode;
import com.hk.commons.vo.ProductInfoApiReq;
import com.hk.commons.vo.ProductInfoApiRes;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 为债权匹配提供产品api
 * @author 会飞的狼 on 2017/10/31.
 */
@Controller
@RequestMapping(value = BaseCtrl.App + "/ProductInfoApi")
public class ProductInfoForApiCtrl extends BaseCtrl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 产品列表
     * @param req
     */
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseBase<List<ProductInfoApiRes>> list(@RequestBody ProductInfoApiReq req) {
        ResponseBase<List<ProductInfoApiRes>> resp = new ResponseBase<List<ProductInfoApiRes>>();

        Map<String, Object> queryForMap = this.jdbcTemplate.queryForMap(
                buildCountSQL(req.getProductCode(), req.getProductName(), req.getIssuerId()));
        Integer total = Integer.valueOf(queryForMap.get("total").toString()) ; //求total总和

        String sql = buildSelectSQL(req.getProductCode(), req.getProductName(),req.getIssuerId(), req.getCurPage(),req.getPageSize());

        List<ProductInfoApiRes> result = queryList(sql);

        JSONArray jsonArray = JSONArray.fromObject(result);
        resp.setResult(jsonArray);
        resp.setSize(total);

        return resp;
    }

    /**
     * 产品对应的订单信息
     * @param productId
     */
    @ResponseBody
    @RequestMapping(value = "/getOrder", method = RequestMethod.GET)
    public ResponseBase getOrder(@RequestParam(value = "productId") String productId) {
        logger.info("request productId{}", productId);
        ResponseBase responseBase = new ResponseBase();
        Object msg = null;
        if(productId != null) {
            try {
                msg = jdbcTemplate.queryForList( "SELECT orderId, userRealName,userPhone,userIdentityNo,SUM(successAmount) as successAmount FROM orderView where productId=? group by orderId", new Object[] {productId});
                responseBase.setResult(msg);
            } catch (Exception e) {
                logger.error("code error = ", e);
                responseBase.setResult(e);
                responseBase.setResultCode(ResultCode.FAILED.getCode());
                responseBase.setMsg(ResultCode.FAILED.getMsg());
            }
        }
        if(msg == null) {
            responseBase.setResult(msg);
            responseBase.setResultCode(ResultCode.FAILED.getCode());
            responseBase.setMsg(ResultCode.FAILED.getMsg());
        }
        return responseBase;
    }

    /**
     * 获取发行方
     */
    @ResponseBody
    @RequestMapping(value = "/getIssuerId", method = RequestMethod.GET)
    public ResponseBase getOrder() {
        logger.info("request getIssuerId{}");
        ResponseBase responseBase = new ResponseBase();
        Object msg = null;
            try {
                msg = jdbcTemplate.queryForList( "SELECT id,name FROM t_company_info ");
                if(msg != null) {
                    responseBase.setResult(msg);
                    responseBase.setResultCode(ResultCode.SUCC.getCode());
                    responseBase.setMsg(ResultCode.SUCC.getMsg());
                }
            } catch (Exception e) {
                logger.error("code error = ", e);
                responseBase.setResult(e);
                responseBase.setResultCode(ResultCode.FAILED.getCode());
                responseBase.setMsg(ResultCode.FAILED.getMsg());
                return responseBase;
            }

        return responseBase;
    }


    private String buildCountSQL(String proNo, String name, Integer issuer ) {
        StringBuffer sb = new StringBuffer();
        sb.append(" select  ");
        sb.append(" count(1) as total ");
        sb.append(" FROM    ");
        sb.append(" t_product_info p ");

        buildWhereSQL(proNo, name,issuer, sb);

        return sb.toString();
    }

    private void buildWhereSQL(String proNo, String name, Integer issuer, StringBuffer sb) {
        sb.append(" where 1=1   ");

        if (StringUtils.isNotEmpty(proNo)) {
            sb.append(" and (p.proNo like '%" + proNo + "%' )");
        }

        if(StringUtils.isNotEmpty(name)) {
            sb.append(" and (p.name like '%" + name + "%' )");
        }

        if (issuer != null) {
            sb.append(" and  p.issuerId =  " + issuer + " ");
        }
    }

    private String buildSelectSQL(String proNo, String name, Integer issuer, Integer curPage, Integer pageSize) {
        StringBuffer sb = new StringBuffer();
        sb.append(" select  ");
        sb.append(" p.id , ");
        sb.append(" p.proNo , ");
        sb.append(" p.name , ");
        sb.append(" p.proStatus , ");
        sb.append(" p.issuerId ,");
        sb.append(" p.startSaleTime , ");
        sb.append(" p.endSaleTime , ");
        sb.append(" p.saleOut , ");//是否满标
        sb.append(" p.yraiseAccount , ");//募集额度
        sb.append(" p.financingAccount  ");//已募集金额
        sb.append(" FROM    ");
        sb.append(" t_product_info p  ");

        buildWhereSQL(proNo, name, issuer, sb);
        sb.append(" ORDER BY p.id DESC ");

        if(curPage != null && pageSize!=null){
            Integer offset = pageSize*(curPage-1);
            Integer rows = pageSize;
            sb.append(" limit "+offset+","+rows+" ");
        }

        return sb.toString();
    }

    private List<ProductInfoApiRes> queryList(String sql) {
        List<Map<String, Object>> productList = this.jdbcTemplate.queryForList(sql);

        return productList
                .parallelStream()
                .map(map ->{
                    ProductInfoApiRes productInfoRes = new ProductInfoApiRes();

                    Object proNo = map.get("proNo");
                    if(proNo != null) {
                        productInfoRes.setProductCode(map.get("proNo").toString());
                    }
                    productInfoRes.setProductName(map.get("name").toString());
                    productInfoRes.setProStatus(Integer.valueOf(map.get("proStatus").toString()));
                    if(map.get("startSaleTime") != null) {
                        productInfoRes.setStartSaleTime(map.get("startSaleTime").toString());
                    }
                    if(map.get("endSaleTime") != null) {
                        productInfoRes.setEndSaleTime(map.get("endSaleTime").toString());
                    }

                    BigDecimal yraiseAccount = BigDecimal.ZERO;
                    if(map.get("yraiseAccount") != null) {
                        yraiseAccount = (BigDecimal) map.get("yraiseAccount");
                        productInfoRes.setYraiseAccount(yraiseAccount);
                    }

                    BigDecimal financingAccount = BigDecimal.ZERO;
                    if(map.get("financingAccount") != null) {
                        financingAccount = (BigDecimal) map.get("financingAccount");
                        productInfoRes.setFinancingAccount(financingAccount);
                    }

                    //发行方
                    if(map.get("issuerId") != null) {
                        Integer issuerId = Integer.parseInt(map.get("issuerId").toString());
                        productInfoRes.setIssuerId(issuerId);
                    }

                    //是否满标
                    if(map.get("saleOut") != null) {
                        if(map.get("saleOut").toString().equals("1")) {
                            productInfoRes.setFull(true);
                        }else {
                            productInfoRes.setFull(false);
                        }
                    }

                    if(map.get("id") != null) {
                        String productId = map.get("id").toString();
                        productInfoRes.setId(productId);
                        Integer orderNum = null;
                        orderNum =  (Integer)jdbcTemplate.queryForObject( "SELECT count(id) FROM t_order_info WHERE productId = ?", new Object[] {productId}, java.lang.Integer.class);
                        productInfoRes.setParticipateNumber(orderNum);
                    }

                    return productInfoRes;
                })
                .collect(Collectors.toList());
    }
}
